// order//order/orderDetail/index.js
const app = getApp();
const util = require('../../../utils/util.js');
const utils = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    oid: 0,
    orderInfo: '',
    freeMoney: 0, //满多少免配送费
    minLimit: 0, //多少起送
    isBoss: 0, //0用户1商家
    bossname: '',
    isCoupon: 0,
    showCut: false,
    latitude: 22.52291,
    longitude: 114.05454,
    markers: [],
    riderUid: 0,
    riderName: '',
    riderMobile: '',
    showMap: false,
    riderInfo: {Mobile: ''},
    shipType: 0,  //配送类型： 1 快递配送, 2 同城配送
    shipCoId: 0 //配送公司ID
  },

  callBoss: function () {
    let mobile = this.data.orderInfo.Mobile;
    if (mobile) {
      wx.makePhoneCall({
        phoneNumber: mobile
      })
    }
  },

  // 骑手信息
  getRiderInfo: function (riderUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Rider/GetRider?uid=' + riderUid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let riderInfo = that.data.riderInfo;
            riderInfo.Name = res.data.Data.Name;
            riderInfo.Mobile = res.data.Data.Mobile;
            that.setData({
              riderInfo: riderInfo
            })
          }
        }
      }
    })
  },
  callRider: function () {
    let mobile = this.data.riderInfo.Mobile;
    if (mobile) {
      wx.makePhoneCall({
        phoneNumber: mobile
      })
    }
  },

  // 刷新骑手位置
  refreshLocation: function () {
    let that = this;   
    let path = '';
    let shipName = that.data.orderInfo.OrderInfo.ShipCoName;
    if(shipName.indexOf('企动')>-1){
      path = '/api/Rider/GetRider?uid=' + that.data.riderUid
    }
    if(shipName.indexOf('顺丰同城')>-1 || shipName.indexOf('聚合')>-1){
      path = '/api/ship/GetRiderLocation?oid=' + that.data.oid;
    }else{
      return;
    }
    wx.showLoading({title: '正在更新...',})
    wx.request({
      url: app.globalData.host + path,
      success: function (res) {
        if (res.data.Code == 0) {
          wx.hideLoading();
          if (res.data.Data) {
            let riderInfo = that.data.riderInfo;
            let markers = [];
            let info = {
              id: 0,
              latitude:  res.data.Data.Latitude,
              longitude: res.data.Data.Longitude,
              iconPath: '/images/nav/riderLocation.png',
              title: '',
              width: 34,
              height:34,
            };          
            markers.push(info);
            if(res.data.Data.RiderPhone){
              riderInfo.Name = res.data.Data.RiderName;
              riderInfo.Mobile = res.data.Data.RiderPhone;
            }
            that.setData({
              markers: markers,
              latitude: info.latitude,
              longitude: info.longitude,
              riderInfo: riderInfo,
              showMap: true
            })
          }
        }
      }
    })
  },

  copyAddress: function () {
    let orderInfo = this.data.orderInfo;
    let str = orderInfo.RegionInfo.ProvinceName + orderInfo.RegionInfo.CityName + orderInfo.RegionInfo.Name + orderInfo.OrderInfo.Address;
    utils.copyData(str, '地址');
  },

  copyMobile: function () {
    let orderInfo = this.data.orderInfo;
    let str = orderInfo.OrderInfo.Consignee + "  " + orderInfo.OrderInfo.Mobile;
    utils.copyData(str, '联系方式');
  },

  copyOSN: function () {
    let orderInfo = this.data.orderInfo;
    let str = orderInfo.OrderInfo.OSN.toString();
    utils.copyData(str, '订单号');
  },

  // 订单详情
  getOrderDetail: function (oid, uid) {
    let that = this;
    if(!uid){
      if(app.globalData.userInfo){
        uid = app.globalData.userInfo.Uid
      }else{
        setTimeout(function(){
          that.getOrderDetail(oid, uid);
        },1000)
        return;
      }
    }
    wx.request({
      url: app.globalData.host + '/api/order/GetOrder?uid=' + uid + '&oid=' + oid,
      success: function (res) {
        if (res.data.Code == 0) {
          let info = res.data.Data;
          let orderProductList = info.OrderProductList;
          for (let i = 0; i < orderProductList.length; i++) {
            orderProductList[i].optionsName = '';
            orderProductList[i].Info.ShowImg = that.formatImg(orderProductList[i].Info.ShowImg);
            if (orderProductList[i].OptionList.length > 0) {
              let optionidList = orderProductList[i].OptionList;
              for (let j = 0; j < optionidList.length; j++) {
                orderProductList[i].optionsName += optionidList[j].Name + '、';
              }
              orderProductList[i].optionsName = orderProductList[i].optionsName.substr(0, orderProductList[i].optionsName.length - 1);
            }
          }
          if (info.OrderInfo.Sid.trim()) {
            info.OrderInfo.Sid = info.OrderInfo.Sid.trim().replace(' ', ' | ');
          }
          info.OrderInfo.allCutMoney = 
              info.OrderInfo.CouponMoney + 
              info.OrderInfo.CardDiscountMoney + 
              info.OrderInfo.CardItemMoney + 
              info.OrderInfo.Discount;
      
          //骑手
          let riderInfo = that.data.riderInfo;
          if (info.OrderActionInfo && info.OrderActionInfo.length > 0) {
            riderInfo.State = info.OrderActionInfo[0].ActionDes;
            for (let k = 0; k < info.OrderActionInfo.length; k++) {
              if (info.OrderActionInfo[k].ActionType == 100) {
                riderInfo.receiveTime = info.OrderActionInfo[k].ActionTime;
                break;
              }
            }
          }
          that.setData({
            orderInfo: info,
            riderInfo: riderInfo
          })
          
          let shipName = info.OrderInfo.ShipCoName;     
          if(shipName.indexOf('企动')>-1){
            that.getRiderUid(oid);   //企动快送-骑手位置
          }
          if(shipName.indexOf('顺丰同城')>-1 || shipName.indexOf('聚合')>-1){
            that.refreshLocation();  //骑手位置
          }
        } else {
          util.showModal(res.data.Message);          
        }
      }
    })
  },
  formatImg: function(showImg){
    if (showImg.indexOf('ps') != -1) {
      return utils.formatAvaterByProHead(showImg);
    }
    return utils.formatAvater(showImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
  },
  // 商家信息
  getInfo: function () {
    let that = this;
    let cardid = wx.getStorageSync("cardId");
    if (cardid) {
      wx.request({
        url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardid,
        success: function (res) {
          if (res.data.Code == 0) {
            that.getDeliverySet(res.data.Data.Uid);
          }
        }
      })
    }
  },
  // 商家配送费
  getDeliverySet: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Ship/GetShip?uid=' + uid,
      success: function (res) {
        if (res.data.Code == 0 && res.data.Data) {
          let item = res.data.Data;
          that.setData({
            shipCoId: item.ShipCoId,
            shipType: item.ShipType,
            minLimit: item.MinLimit, //最低起送
            freeMoney: item.FreeLimit
          })
        } 
      }
    })
  },
  showCut: function () {
    this.setData({
      showCut: !this.data.showCut
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.iscoupon) {
      this.setData({
        isCoupon: options.iscoupon
      })
    }
    if (options.oid) {
      this.getOrderDetail(options.oid, options.uid);
      this.getInfo();
      this.data.oid = options.oid;
    }
    if (options.isBoss) {
      this.setData({
        isBoss: options.isBoss
      })
    }
  },
  //企动快送-骑手信息
  getRiderUid: function (oid) {
    let that = this;
    that.setData({showMap: true})
    wx.request({
      url: app.globalData.host + '/api/porder/OrderByOid?oid=' + oid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data && res.data.Data.RiderUid > 0) {
            that.data.riderUid = res.data.Data.RiderUid;
            that.refreshLocation();
            that.getRiderInfo(res.data.Data.RiderUid);
            
          }
        } else {
          util.showModal(res.data.Message);       
        }
      },
    })
  },

  // 发货
  sendOrderProduct: function (e) {
    let that = this;
    let oid = e.currentTarget.dataset.oid;
    var shipCoId = that.data.shipCoId;  
    var shipType = that.data.shipType;  
    let shipName = '';
    //快递方式发货
    if(shipType == 1){
      wx.navigateTo({
        url: '/pages/h5page/index?url=' + encodeURIComponent(app.globalData.webhost + 'order-send.html?oid=' + oid+'&uid=' + app.globalData.userInfo.Uid),
      });
      return;
    }
   
    switch(shipCoId){
      case 17: shipName='达达配送'; break; 
      case 28: shipName='顺丰同城'; break; 
      case 26: shipName='企动快送'; break; 
      case 11: shipName='商家配送'; break; 
      case 29: shipName='聚合配送'; break; 
     }
    if(shipCoId == 0){
      utils.showModal('未完善配送方式，请前往[设置-外卖设置-配送方式]页面完善');
      return;
    }    
    wx.showModal({
      title: '提示',
      content: '发货方式为' + shipName + '，是否确认发货?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Order/SendOrderProduct?uid=' + app.globalData.userInfo.Uid + '&oid=' + oid + '&shipCoId=' + shipCoId + '&shipSn=711688',
            success: function (res) {
              if (res.data.Code == 0) {
                utils.showToast('发货成功');
                that.getOrderDetail(oid, app.globalData.userInfo.Uid);
              } else {
                utils.showModal(res.data.Message);               
              }
            }
          })
        }
      }
    })
  },

  // 收货
  receiveOrder: function (e) {
    let that = this;
    let oid = e.currentTarget.dataset.oid;
    wx.showModal({
      title: '提示',
      content: '是否确认收货？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Order/ReceiveOrder?uid=' + app.globalData.userInfo.Uid + '&oid=' + oid,
            success: function (res) {
              if (res.data.Code == 0) {
                wx.showToast({
                  mask: true,
                  title: '订单已完成',
                  duration: 500
                })
                that.getOrderDetail(oid, app.globalData.userInfo.Uid);
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },
  toLogistics: function(e){
    let oid = e.currentTarget.dataset.oid;
    wx.navigateTo({
      url: '/order/order/logistics/index?oid=' + oid,
    })
  },
  // 确认/拒绝退款（1同意0拒绝）
  sureRefund: function (e) {
    let that = this;
    let oid = e.currentTarget.dataset.oid; //退款申请id
    let state = e.currentTarget.dataset.state;
    let mesg = '是否确认退款?'
    if (state == 0) {
      mesg = '是否拒绝退款?'
    }
    wx.showModal({
      title: '提示',
      content: mesg,
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/OrderAfter/GetAfterOrder?oid=' + oid,
            success: function (res) {
              if (res.data.Code == 0) {
                if (res.data.Data.ASId) {
                  that.confirmRefund(res.data.Data.ASId, state);
                } else {
                  wx.showModal({
                    title: '提示',
                    content: '退款失败',
                    showCancel: false
                  })
                }

              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },
  confirmRefund: function (asid, state) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/OrderAfter/CheckRefund?asId=' + asid + '&uid=' + app.globalData.userInfo.Uid + '&state=' + state,
      success: function (res) {
        if (res.data.Code == 0) {     
          util.showToast('退款审核完成');
          that.getOrderDetail(oid, app.globalData.userInfo.Uid);
        } else {
          util.showModal(res.data.Message);          
        }
      }
    })
  },

  onShareAppMessage: function () {
    let that= this;
    return {
      path: '/order/order/orderDetail/index?oid=' + that.data.oid,
      success: function (res) {
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      }
    }
  }
})